package com.leejxx.health.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.leejxx.health.common.MessageConst;
import com.leejxx.health.entity.Result;
import com.leejxx.health.service.ReportService;
import com.leejxx.health.pojo.MemberReport;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

/**
 * @Author LeeJx
 * @ClassName ReportController
 * @Description TODO
 * @date 2021/1/10 12:41
 * @Version 1.0
 */
@RestController
@Slf4j
@RequestMapping("/report")
public class ReportController {
    @DubboReference
    private ReportService reportService;

    @RequestMapping("/getMemberReport")
    public Result getMemberReport() {
        MemberReport memberReport = reportService.getMemberReport();
        log.info("[会员分析-数量统计]:data:{}", memberReport);
        return new Result(true, MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS, memberReport);
    }

    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport() {
        Map<String, Object> map = reportService.getSetMealReport();
        log.info("[套餐分析-数量统计]:data:{}", map);
        return new Result(true, MessageConst.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
    }

    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
        Map<String, Object> map = reportService.getBusinessReportData();
        log.info("[运营报告-数量统计]:data:{}", map);
        return new Result(true, MessageConst.GET_BUSINESS_REPORT_SUCCESS, map);
    }

    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletResponse response) {
        log.info("[导出运营数据报表]开始...");

        Map<String, Object> map = reportService.getBusinessReportData();
        log.info("[导出运营数据报表]data:{}", map);
        Object reportDate = map.get("reportDate");

        TemplateExportParams params = new TemplateExportParams("health_oms_backend/src/main/resources/report_template.xlsx");
        Workbook workbook = ExcelExportUtil.exportExcel(params, map);
        try {
            OutputStream os = response.getOutputStream();
            //4-写入网络输出流
            //写入返回流
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;fileName=" + reportDate + "_report.xlsx");
            workbook.write(os);
            log.info("[导出运营数据报表]完成...");
            return null;
        } catch (IOException e) {
            log.error("",e);
            return new Result(false,MessageConst.ACTION_FAIL);
        }
    }
}
